/**
 * Created by zhangbo on 20/12/17.
 */

var CameraPath = (function () {

    function _(pathContainer, cesiumViewer, opt) {
        var options = this._options = opt || {width: '', height: '100%'};
        this._speed = 1;
        this._loop = false;//循环
        this._turnback = false;//折返
        this._backward = false;//反向
        this._edit = false;
        this._paths = [];
        this._positions = [];
        this._positionsFirstPerson = [];
        this._drawLinePoints = [];
        this._index = 0;
        this._play = false;
        this._pause = false;
        this._firstPerson = false;//第一人称视图
        this._turnbackOrientation = 'positive';//positive negative 
        this._viewer = cesiumViewer;
        this._handler = new Cesium.ScreenSpaceEventHandler(cesiumViewer.scene.canvas);
        this._editPathFrames = [];
        this._cameraPathList = [];
        this._selectCamaraPath = null;
        this._openLayerIndex;
        var _this = this;

        this._container = document.getElementById(pathContainer);
        var cameraRect = document.createElement('div');
        cameraRect.className = 'camera-rect';
        cameraRect.style.display = 'none';
        document.body.appendChild(cameraRect);
        var listDiv = document.createElement('div');
        listDiv.setAttribute('id', 'cameraPathsListMain');
        listDiv.className = 'path-list';
        var createBtnDiv = document.createElement('div');
        createBtnDiv.style.height = '30px';
        var editBtn = document.createElement('div');
        editBtn.className = 'btn-list-new btn editBtn';
        editBtn.innerHTML = '漫游编辑';
        var stopBtn = document.createElement('div');
        stopBtn.className = 'btn-list-add btn stopBtn';
        stopBtn.innerHTML = '停止播放';
        createBtnDiv.appendChild(editBtn);
        createBtnDiv.appendChild(stopBtn);
        this._container.appendChild(listDiv);
        this._container.appendChild(createBtnDiv);

        editBtn.onclick = function (e) {
            if (_this._openLayerIndex) {
                return;
            }
            _this._openLayerIndex = layer.open({
                type: 1,
                shade: false,
                area: ['553px', 'auto'],
                maxmin: false,
                resize: false,
                offset: 'lb',
                title: '漫游编辑',
                shadeClose: true, //点击遮罩关闭
                content: _this._editUIHtml(),
                success: function (layero, index) {
                    _this._editUIInit();
                },
                cancel: function (index, layero) {
                    _this.stop();
                    _this._edit = false;
                    _this._openLayerIndex = undefined;
                    document.getElementsByClassName('camera-rect')[0].style.display = 'none';
                    document.getElementById('addCameraFrame').innerHTML = '开始添加帧';
                },
                min: function (e) {

                },
                restore: function (e) {

                }
            });
        };
        stopBtn.onclick = function (e) {
            _this.stop();
        }

        this._editUIHtml = function () {
            return '<div class="camera-edit">\n' +
                '    <div class="camera-edit-list">\n' +
                '        <div id="cameraPathsList" class="list"></div>\n' +
                '        <div class="btn-list">\n' +
                '            <div id="cameraNewPath" class="btn-list-new btn">新建</div>\n' +
                '            <div id="cameraPathDelete" class="btn-list-cancel btn">删除</div>\n' +
                '        </div>\n' +
                '    </div>\n' +
                '    <div class="camera-edit-content">\n' +
                '        <div class="camera-edit-control">\n' +
                '            <div>\n' +
                '                <div id="cameraPlay" class="btn-play"></div>\n' +
                '                <div id="cameraPause" class="btn-pause"></div>\n' +
                '                <div id="cameraStop" class="btn-stop"></div>\n' +
                '            </div>\n' +
                '            <div>\n' +
                '                <div id="rategroup">\n' +
                '                    <label>速率：</label>\n' +
                '                </div>\n' +
                '                <div id="schemagroup" >\n' +
                '                    <label>模式：</label>\n' +
                '                </div>\n' +
                '            </div>\n' +
                '        </div>\n' +
                '        <div class="camera-edit-frame">\n' +
                '            <div class="name-div">\n' +
                '                名称：<input id="cameraPathName" type="text"/><span id="cameraPathNameWarnning" style="font-size:12px;color:red;display:none;position:absolute;top:7px;left:55px;">请填写名称</span>\n' +
                '                <div id="addCameraFrame" class="btn-list-add add">开始添加帧</div>\n' +
                '                <div id="cameraSave" class="btn-list-save save">保存</div>\n' +
                '            </div>\n' +
                '            <div class="frame-list">\n' +
                '                <div id="cameraEditFrames"></div>\n' +
                '            </div>\n' +
                '        </div>\n' +
                '    </div>\n' +
                '</div>';
        };

        this._editUIInit = function () {
            var cameraPlay = document.getElementById('cameraPlay');
            var cameraPause = document.getElementById('cameraPause');
            var cameraStop = document.getElementById('cameraStop');
            var cameraSave = document.getElementById('cameraSave');
            var addCameraFrame = document.getElementById('addCameraFrame');
            var cameraNewPath = document.getElementById('cameraNewPath');
            var cameraPathName = document.getElementById('cameraPathName');
            var cameraPathDelete = document.getElementById('cameraPathDelete');
            // var cameraX2 = document.getElementById('cameraX2');
            // var cameraX5 = document.getElementById('cameraX5');
            // var cameraX10 = document.getElementById('cameraX10');
            // var cameraPathCreate = document.getElementById('cameraPathCreate');
            // var cameraPathTab = document.getElementById('tab1');
            // var cameraPathTabFirstPerson = document.getElementById('tab2');
            // var cameraPathEdit = document.getElementById('cameraPathEdit');
            // var cameraClearPath = document.getElementById('cameraClearPath');
            // var cameraClearPathFirstPerson = document.getElementById('cameraClearPathFirstPerson');

            cameraPlay.onclick = function () {
                _this.play();
            }
            cameraPause.onclick = function () {
                _this.pause();
//                cameraPause.value = _this._pause ? '继续' : '暂停';
            }
            cameraStop.onclick = function () {
                _this.stop();
            }
            cameraSave.onclick = function () {
                var pathName = document.getElementById('cameraPathName');
                var pathNameWarnning = document.getElementById('cameraPathNameWarnning');
                if (pathName.value === '') {
                    pathNameWarnning.style.display = 'block';
                    return;
                }
                _this.savePath(pathName.value, _this.getPathJson());
            }
            cameraNewPath.onclick = function () {
                document.getElementById('cameraPathName').value = '漫游路径（' + _this._cameraPathList.length + '）';
                _this._positions = [];
                _this._editPathFrames = [];
                _this._pathFrameRefresh();
            }
            addCameraFrame.onclick = function () {
                if (!_this._edit) {
                    document.getElementsByClassName('camera-rect')[0].style.display = 'block';
                    this.innerHTML = '停止添加帧';
                    _this._edit = true;
                }
                else {
                    document.getElementsByClassName('camera-rect')[0].style.display = 'none';
                    this.innerHTML = '开始添加帧';
                    _this._edit = false;
                }
            }
            cameraPathName.oninput = function () {
                if (this.value !== '') {
                    document.getElementById('cameraPathNameWarnning').style.display = 'none';
                }
            }
            cameraPathDelete.onclick = function () {
                if (_this._selectCamaraPath) {
                    _this.deletePath(_this._selectCamaraPath.bh);
                }
            }
            AirportUI.checkBoxGroup(
                '#schemagroup',
                [{label: '循环', value: 'loop'}, {label: '往返', value: 'return'}, {label: '反向', value: 'backward'}],
                function (checkDom, data) {
                    if (data.value === 'loop') {
                        _this._loop = data.selected;
                    }
                    else if (data.value === 'return') {
                        _this._turnback = data.selected;
                    }
                    else if (data.value === 'backward') {
                        _this._backward = data.selected;
                        if (_this._paths) {
                            _this._paths.reverse();
                        }
                    }
                },
                'checkbox-margin'
            )
            AirportUI.radioBoxGroup(
                '#rategroup',
                [{label: 'x1', value: 1, selected: true}, {label: 'x2', value: 2}, {
                    label: 'x5',
                    value: 5
                }, {label: 'x10', value: 10}, {label: 'x100', value: 100}],
                function (radioDom, data) {
                    _this._speed = data.value;
                },
                'checkbox-margin'
            )

            this._pathListRefresh();
        };

        this._eventHandler = function (e) {
            if (e.keyCode === 32) {//space
                if (Cesium.defined(_this._viewer) && _this._edit) {
                    var camera = _this._viewer.camera;
                    var position = camera.position;
                    var heading = camera.heading;
                    var pitch = camera.pitch;
                    var roll = camera.roll;

                    _this._positions.push({
                        position: position.clone(new Cesium.Cartesian3()),
                        hpr: {
                            heading: heading,
                            pitch: pitch,
                            roll: roll
                        }
                    });

                    _this._editPathFrames.push({
                        frame: {
                            position: position.clone(new Cesium.Cartesian3()),
                            hpr: {
                                heading: heading,
                                pitch: pitch,
                                roll: roll
                            }
                        },
                        // index: _this._positions.length - 1
                    });
                    _this._pathFrameRefresh();
                    _this.createPath();
                }
            }
        };

        this._clickAction = function (click) {
            if (_this._firstPerson && _this._edit) {
                if (Cesium.defined(click.position)) {
                    var position = _this._viewer.scene.camera.pickEllipsoid(click.position, Cesium.Ellipsoid.WGS84);
                    if (Cesium.defined(position)) {
                        var cg = Cesium.Cartographic.fromCartesian(position);
                        _this._positionsFirstPerson.push(Cesium.Cartesian3.fromDegrees(Cesium.Math.toDegrees(cg.longitude), Cesium.Math.toDegrees(cg.latitude), 10));

                        var cameraPathEditViews = document.getElementById('cameraPathEditFirstPerson');
                        var li = document.createElement('li');
//                        li.innerHTML = '<span class="label">第 ' + _this._positions.length + ' 帧</span><a class="camera-path-control">查看</a><a class="camera-path-control">删除</a>';
                        li.innerHTML = '<span class="label">第 ' + _this._positionsFirstPerson.length + ' 帧</span>';
                        var viewBtn = document.createElement('a');
                        viewBtn.className = 'camera-path-control';
                        viewBtn.innerHTML = '查看';
                        viewBtn.setAttribute('index', _this._positionsFirstPerson.length - 1);
                        viewBtn.onclick = function (e) {
                            var e = event || window.event, target = e.target || e.srcElement;
                            console.log(target)
                            var index = parseInt(target.getAttribute('index'));
                            var v = _this._positionsFirstPerson[parseInt(target.getAttribute('index'))];
                            var cartographic = Cesium.Cartographic.fromCartesian(v);
                            var postion = Cesium.Cartesian3.fromDegrees(Cesium.Math.toDegrees(cartographic.longitude), Cesium.Math.toDegrees(cartographic.latitude), 3000);
                            var camera = _this._viewer.camera;
                            camera.setView({
                                destination: postion,
                                orientation: {
                                    heading: camera.heading, // east, default value is 0.0 (north)
                                    pitch: Cesium.Math.toRadians(-90.0),    // default value (looking down)
                                    roll: 0.0                             // default value
                                }
                            });
                        }
                        li.appendChild(viewBtn);
                        cameraPathEditViews.appendChild(li);

                        _this.drawPath();
                    }
                }
            }

        }

        this._handler.setInputAction(this._clickAction, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        document.addEventListener('keydown', this._eventHandler);
        viewer.scene.preRender.addEventListener(this.preRender, this);

        //初始读取漫游路径列表
        this.getPathNames(function (names) {
            AirportUI.verticalList(
                '#cameraPathsListMain',
                names,
                function (e, selectedItem) {
                    _this._selectCamaraPath = selectedItem;
                    _this.stop();
                    //调取漫游路径数据
                    AirportService.asyncQueryGet(AirportService.URLs.QT.MYXX.getByIdUrl + '?id=' + selectedItem.bh, function (data) {
                        var dataPath = data['data'];
                        if (dataPath) {
                            var bh = dataPath.bh;
                            var mymc = dataPath.mymc;
                            var mysj = dataPath.mysj;
                            // var paths = JSON.parse(dataArr[i].mysj);
                            // cb(mysj);
                            _this.setPath(JSON.parse(mysj));
                            _this.play();
                        }
                    });
                },
                function (index, item) {
                    return '<div class="list-item" data-bh="' + item.bh + '" title="' + item.mymc + '">' + item.mymc + '</div>';
                }
            )
        });
    };

    _.prototype.getPathNames = function (cb) {
        //调取漫游路径名称列表
        AirportService.asyncQueryGet(AirportService.URLs.QT.MYXX.getNamesUrl, function (data) {
            var dataArr = data['data'];
            if (typeof cb === 'function') {
                cb(dataArr);
            }
        });
    };

    _.prototype.getPath = function (bh, cb) {
        //调取漫游路径数据
        AirportService.asyncQueryGet(AirportService.URLs.QT.MYXX.getByIdUrl + '?id=' + bh, function (data) {
            var dataArr = data['data'];
            var bh = dataArr.bh;
            var mymc = dataArr.mymc;
            var mysj = dataArr.mysj;
            // var paths = JSON.parse(dataArr[i].mysj);
            cb(mysj);
        });
    };

    _.prototype.savePath = function (mymc, mysj) {
        //保存漫游路径
        var _this = this;
        _this.stop();
        AirportService.asyncQueryPost(AirportService.URLs.QT.MYXX.saveUrl, {mymc: mymc, mysj: mysj}, function (data) {
            if (data && data.count === 1) {
                _this._pathListRefresh();
            }
        });
    };

    _.prototype.deletePath = function (bh) {
        var _this = this;
        _this.stop();
        //删除漫游路径
        AirportService.asyncQueryPost(AirportService.URLs.QT.MYXX.deleteByIdUrl, {bh: bh}, function (data) {
            console.log(data);
            _this._pathListRefresh();
        });
    };

    _.prototype.play = function () {
        this._pause = false;
        this._play = true;
        this._index = 0;
        this._turnbackOrientation = 'positive';
    };

    _.prototype.stop = function () {
        this._play = false;
        this._pause = false;
        this._index = 0;
        if (this._paths.length > 0) {
            if (this._firstPerson) {

            }
            else {
                this._viewer.scene.camera.setView(this._paths[0]);
            }

        }
        // window.clearInterval(this._intervalId);
    };

    _.prototype.pause = function () {
        this._pause = !this._pause;
    };

    _.prototype.edit = function (t) {
        if (t) {
            this.stop();
//            this._play = false;
//            document.getElementById('cameraPathEditViews').innerHTML = '';
//            this._positions = [];
//            this._index = 0;
        }

        this._edit = t;
    };

    _.prototype.preRender = function (scene, time) {
        if (this._play && !this._pause) {
            if (this._turnback) {
                if (this._turnbackOrientation === 'negative') {
                    if (this._index >= 0 && this._index < this._paths.length) {
                        if (this._firstPerson) {
                            if (this._index < this._paths.length - 1) {
                                var p1 = this._paths[this._index + 1];
                                var p2 = this._paths[this._index];
                                if (Cesium.defined(p1) && Cesium.defined(p2) && Cesium.defined(p1) && !Cesium.Cartesian3.equals(p1, p2)) {//当两个点存在且不相等时执行
                                    var velocityResult = new Cesium.Cartesian3();
                                    var velocity = Cesium.Cartesian3.subtract(p2, p1, velocityResult);
                                    Cesium.Cartesian3.normalize(velocity, velocityResult);
                                    Cesium.Cartesian3.divideByScalar(velocity, 1, velocityResult);

                                    var rotationScratch = new Cesium.Matrix3();
                                    Cesium.Transforms.rotationMatrixFromPositionVelocity(p1, velocityResult, Cesium.Ellipsoid.WGS84, rotationScratch);
                                    //var quaternion = Cesium.Quaternion.fromRotationMatrix(rotationScratch);
                                    //_planePrimitive.orientation = quaternion;

                                    var dir = Cesium.Matrix3.getColumn(rotationScratch, 0, new Cesium.Cartesian3());
                                    var up = Cesium.Matrix3.getColumn(rotationScratch, 2, new Cesium.Cartesian3());
                                    scene.camera.setView({
                                        destination: p2,
                                        orientation: {
                                            direction: dir,
                                            up: up
                                        }
                                    });
                                }
                            }
                        }
                        else {
                            scene.camera.setView(this._paths[this._index]);
                        }

                        if (this._index > 0) {
                            this._index = Math.max(this._index - this._speed, 0);
                        }
                        else if (this._index === 0) {
                            if (this._loop) {
                                this._turnbackOrientation = 'positive';
                            }
                            else {
                                //停止播放
                                this.stop();
                            }
                        }
                    }
                }
                else {
                    if (this._index >= 0 && this._index < this._paths.length) {
                        if (this._firstPerson) {
                            if (this._index > 0) {
                                var p1 = this._paths[this._index - 1];
                                var p2 = this._paths[this._index];
                                if (Cesium.defined(p1) && Cesium.defined(p2) && Cesium.defined(p1) && !Cesium.Cartesian3.equals(p1, p2)) {//当两个点存在且不相等时执行
                                    var velocityResult = new Cesium.Cartesian3();
                                    var velocity = Cesium.Cartesian3.subtract(p2, p1, velocityResult);
                                    Cesium.Cartesian3.normalize(velocity, velocityResult);
                                    Cesium.Cartesian3.divideByScalar(velocity, 1, velocityResult);

                                    var rotationScratch = new Cesium.Matrix3();
                                    Cesium.Transforms.rotationMatrixFromPositionVelocity(p1, velocityResult, Cesium.Ellipsoid.WGS84, rotationScratch);
                                    //var quaternion = Cesium.Quaternion.fromRotationMatrix(rotationScratch);
                                    //_planePrimitive.orientation = quaternion;

                                    var dir = Cesium.Matrix3.getColumn(rotationScratch, 0, new Cesium.Cartesian3());
                                    var up = Cesium.Matrix3.getColumn(rotationScratch, 2, new Cesium.Cartesian3());
                                    scene.camera.setView({
                                        destination: p2,
                                        orientation: {
                                            direction: dir,
                                            up: up
                                        }
                                    });
                                }
                            }
                        }
                        else {
                            scene.camera.setView(this._paths[this._index]);
                        }

                        if (this._index < this._paths.length - 1) {
                            this._index = Math.min(this._index + this._speed, this._paths.length - 1);
                        }
                        if (this._index === this._paths.length - 1) {
                            this._turnbackOrientation = 'negative';
                        }
                    }
                }
            }
            else {
                if (this._index >= 0 && this._index < this._paths.length) {
                    if (this._firstPerson) {
                        if (this._index > 0) {
                            var p1 = this._paths[this._index - 1];
                            var p2 = this._paths[this._index];
                            if (Cesium.defined(p1) && Cesium.defined(p2) && Cesium.defined(p1) && !Cesium.Cartesian3.equals(p1, p2)) {//当两个点存在且不相等时执行
                                var velocityResult = new Cesium.Cartesian3();
                                var velocity = Cesium.Cartesian3.subtract(p2, p1, velocityResult);
                                Cesium.Cartesian3.normalize(velocity, velocityResult);
                                Cesium.Cartesian3.divideByScalar(velocity, 1, velocityResult);

                                var rotationScratch = new Cesium.Matrix3();
                                Cesium.Transforms.rotationMatrixFromPositionVelocity(p1, velocityResult, Cesium.Ellipsoid.WGS84, rotationScratch);
                                //var quaternion = Cesium.Quaternion.fromRotationMatrix(rotationScratch);
                                //_planePrimitive.orientation = quaternion;

                                var dir = Cesium.Matrix3.getColumn(rotationScratch, 0, new Cesium.Cartesian3());
                                var up = Cesium.Matrix3.getColumn(rotationScratch, 2, new Cesium.Cartesian3());
                                scene.camera.setView({
                                    destination: p2,
                                    orientation: {
                                        direction: dir,
                                        up: up
                                    }
                                });
                            }
                        }
                    }
                    else {
                        scene.camera.setView(this._paths[this._index]);
                    }

                    if (this._index < this._paths.length - 1) {
                        this._index = Math.min(this._index + this._speed, this._paths.length - 1);
                    }
                    else {
                        this._index++;
                    }
                }
                else if (this._loop) {
                    this._index = 0;
                }
                else {
                    //停止播放
                    this.stop();
                }
            }

            // if (this._backward) {
            //     if (this._index >= 0 && this._index < this._paths.length) {
            //         scene.camera.setView(this._paths[this._index]);
            //         if (this._index > 0) {
            //             this._index = Math.max(this._index - this._speed, 0);
            //         }
            //         else{
            //         	this._index--;
            //         }
            //     }
            //     else if (this._index < 0 && this._loop) {
            //         this._index = this._paths.length - 1;
            //     }
            // }
            // else {
            //     if (this._index >= 0 && this._index < this._paths.length) {
            //         scene.camera.setView(this._paths[this._index]);
            //         if(this._index < this._paths.length - 1){
            //         	this._index = Math.min(this._index + this._speed, this._paths.length - 1);
            //         }
            //         else {
            //         	this._index++;
            //         }
            //     }
            //     else if (this._loop) {
            //         this._index = 0;
            //     }
            // }
        }
    };

    _.prototype.createPath = function () {
        this._paths = [];//清空
        if (this._firstPerson) {//第一人称视角轨迹绘制
            var len = this._positionsFirstPerson.length;

            for (var i = 1; i < len; i++) {
                var d = Cesium.Cartesian3.distance(this._positionsFirstPerson[i - 1], this._positionsFirstPerson[i]);
                // var num = Math.floor(d / 10);//每10米插一个值
                var num = Math.floor(d);//每1米插一个值
                if (num === 0) {
                    num = 1;
                }
                else if (num > 5000) {
                    num = 5000;
                }

                for (var j = 0; j < num; j++) {
                    this._paths.push(Cesium.Cartesian3.lerp(this._positionsFirstPerson[i - 1], this._positionsFirstPerson[i], j / num, new Cesium.Cartesian3()));
                }
            }
        }
        else {//拍摄视角轨迹绘制
            var len = this._positions.length;
            for (var i = 1; i < len; i++) {
                var d = Cesium.Cartesian3.distance(this._positions[i - 1].position, this._positions[i].position);
                // var num = Math.floor(d / 10);//每10米插一个值
                var num = Math.floor(d);//每1米插一个值
                if (num === 0) {
                    num = 1;
                }
                else if (num > 5000) {
                    num = 5000;
                }

                for (var j = 0; j < num; j++) {
                    this._paths.push({
                        destination: Cesium.Cartesian3.lerp(this._positions[i - 1].position, this._positions[i].position, j / num, new Cesium.Cartesian3()),
                        orientation: {
                            heading: this._positions[i - 1].hpr.heading + (this._positions[i].hpr.heading - this._positions[i - 1].hpr.heading) * j / num,
                            pitch: this._positions[i - 1].hpr.pitch + (this._positions[i].hpr.pitch - this._positions[i - 1].hpr.pitch) * j / num,
                            roll: this._positions[i - 1].hpr.roll + (this._positions[i].hpr.roll - this._positions[i - 1].hpr.roll) * j / num,
                        }
                    });
                }
            }
        }
    };

    _.prototype.drawPath = function () {
        var positions = this._positionsFirstPerson;
        this._drawLinePoints.push(this._viewer.entities.add({
            id: 'camera_path_point_' + (positions.length - 1),
            position: positions[positions.length - 1],
            point: {
                pixelSize: 10,
                color: Cesium.Color.YELLOW
            }
        }));
        if (!Cesium.defined(this._drawLine)) {
            this._drawLine = viewer.entities.add({
                id: 'camera_path_line',
                polyline: {
                    positions: positions,
                    width: 2,
                    material: Cesium.Color.YELLOW
                }
            });
        }
        else {
            this._drawLine.polyline.positions = positions;
        }
    };

    _.prototype.showPath = function (t) {
        if (Cesium.defined(this._drawLine)) {
            this._drawLine.show = t;
        }
        for (var i = 0; i < this._drawLinePoints.length; i++) {
            this._drawLinePoints[i].show = t;
        }
    };

    _.prototype._pathListRefresh = function () {
        var _this = this;
        this.getPathNames(function (names) {
            _this._cameraPathList = names;
            AirportUI.verticalList(
                '#cameraPathsList',
                names,
                function (e, selectedItem) {
                    _this._selectCamaraPath = selectedItem;
                    _this.stop();
                    //调取漫游路径数据
                    AirportService.asyncQueryGet(AirportService.URLs.QT.MYXX.getByIdUrl + '?id=' + selectedItem.bh, function (data) {
                        var dataPath = data['data'];
                        if (dataPath) {
                            var bh = dataPath.bh;
                            var mymc = dataPath.mymc;
                            var mysj = dataPath.mysj;
                            // var paths = JSON.parse(dataArr[i].mysj);
                            // cb(mysj);
                            _this.setPath(JSON.parse(mysj));
                            _this.play();
                        }
                    });
                },
                function (index, item) {
                    return '<div class="list-item" data-bh="' + item.bh + '" title="' + item.mymc + '">' + item.mymc + '</div>';
                }
            );
            AirportUI.verticalList(
                '#cameraPathsListMain',
                names,
                function (e, selectedItem) {
                    _this._selectCamaraPath = selectedItem;
                    _this.stop();
                    //调取漫游路径数据
                    AirportService.asyncQueryGet(AirportService.URLs.QT.MYXX.getByIdUrl + '?id=' + selectedItem.bh, function (data) {
                        var dataPath = data['data'];
                        if (dataPath) {
                            var bh = dataPath.bh;
                            var mymc = dataPath.mymc;
                            var mysj = dataPath.mysj;
                            // var paths = JSON.parse(dataArr[i].mysj);
                            // cb(mysj);
                            _this.setPath(JSON.parse(mysj));
                            _this.play();
                        }
                    });
                },
                function (index, item) {
                    return '<div class="list-item" data-bh="' + item.bh + '" title="' + item.mymc + '">' + item.mymc + '</div>';
                }
            )
        });
    }

    _.prototype._pathFrameRefresh = function () {
        var _this = this;
        AirportUI.verticalList(
            '#cameraEditFrames',
            _this._editPathFrames,
            function (e, selectedItem) {
                var e = event || window.event, target = e.target || e.srcElement;
                if (target.dataset.action === 'view') {
                    console.log('view:' + selectedItem.label);
                    var v = _this._positions[selectedItem.index];
                    _this._viewer.scene.camera.setView({
                        destination: v.position,
                        orientation: {
                            heading: v.hpr.heading,
                            pitch: v.hpr.pitch,
                            roll: v.hpr.roll,
                        }
                    });
                }
                else if (target.dataset.action === 'delete') {
                	_this.stop();
                    _this._editPathFrames.splice(selectedItem.index, 1);
                    _this._positions.splice(selectedItem.index, 1);
                    _this._pathFrameRefresh();
                    _this.createPath();
                }

            },
            function (index, item) {
                item.index = index;
                return '<div class="list-item frame-list-item"><div class="title">第<span style="margin:0 5px">' + (index + 1) + '</span>帧</div><div class="view" data-action="view"></div><div class="delete" data-action="delete"></div></div>';
            }
        )
    }

    _.prototype.destroy = function () {
        this._handler.removeInputAction(this._clickAction, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        this._handler = null;
        document.removeEventListener('keydown', this._eventHandler);
        viewer.scene.preRender.removeEventListener(this.preRender);
    };

    _.prototype.getPathJson = function () {
        var pathJsonObj = {};
        var paths = [];
        var positions;
        if (this._firstPerson) {
            positions = this._positionsFirstPerson;
            var length = positions.length;
            for (var i = 0; i < length; i++) {
                var p = positions[i];
                paths.push({
                    position: {
                        x: p.x,
                        y: p.y,
                        z: p.z
                    },
                });
            }
        }
        else {
            positions = this._positions;
            var length = positions.length;
            for (var i = 0; i < length; i++) {
                var p = positions[i].position;
                var hpr = positions[i].hpr;
                paths.push({
                    position: {
                        x: p.x,
                        y: p.y,
                        z: p.z
                    },
                    hpr: hpr
                });
            }
        }


        pathJsonObj['loop'] = this._loop;//循环
        pathJsonObj['turnback'] = this._turnback;//折返
        pathJsonObj['backward'] = this._backward;//反向
        pathJsonObj['speed'] = this._speed;//速率
        pathJsonObj['paths'] = paths;//
        pathJsonObj['firstperson'] = this._firstPerson;//是否第一人称视角
        return JSON.stringify(pathJsonObj);
    }

    _.prototype.setPath = function (pathObj) {
        this._loop = pathObj['loop'];//循环
        this._turnback = pathObj['turnback'];//折返
        this._backward = pathObj['backward'];//反向
        this._speed = pathObj['speed'];//速率
        this._firstPerson = pathObj['firstperson'];//是否第一人称视角
        var positions = pathObj['paths'];
        if (this._firstPerson) {
            this._positionsFirstPerson.length = 0;
            var length = positions.length;
            for (var i = 0; i < length; i++) {
                var p = positions[i];
                this._positionsFirstPerson.push(new Cesium.Cartesian3(p.position.x, p.position.y, p.position.z));
            }
        }
        else {
            this._positions.length = 0;
            var length = positions.length;
            for (var i = 0; i < length; i++) {
                var p = positions[i];
                this._positions.push({
                    position: new Cesium.Cartesian3(p.position.x, p.position.y, p.position.z),
                    hpr: p.hpr
                });
            }
        }
        this.createPath();
    }

    return _;
})();
